#include "serial.h"
#include <stdexcept>

serial::serial(const std::string& port, DWORD bitrate = CBR_9600) :
	port_(port),
	bitrate_(bitrate)
{}

void serial::open() 
{
	hSerial = CreateFile(port_.c_str(),
            GENERIC_READ | GENERIC_WRITE,
            0,
            0,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            0);
    
    if (hSerial == INVALID_HANDLE_VALUE) {
        if (GetLastError() == ERROR_FILE_NOT_FOUND) {
            //throw new exception();
        }
        //throw new exception("Some other error occured");
    }
    
    DCB dcbSerialParams;
    
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    
    if (! GetCommState(hSerial, &dcbSerialParams)) {
        //throw new exception("Error getting state");
    }
    
    dcbSerialParams.BaudRate = bitrate_;
    dcbSerialParams.ByteSize = 8;
    dcbSerialParams.StopBits = ONESTOPBIT;
    dcbSerialParams.Parity = NOPARITY;
    
    if (! SetCommState(hSerial, &dcbSerialParams)) {
       // throw new exception("Error setting serial port state");
    }
    
    COMMTIMEOUTS timeouts;
    
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;
    
    if (! SetCommTimeouts(hSerial, &timeouts)) {
       // throw new exception("Error while setting timeouts");
    }
}

void serial::close()
{
    if (hSerial != INVALID_HANDLE_VALUE) {
        CloseHandle(hSerial);
    }
}

DWORD serial::write(void* data, DWORD len)
{
    DWORD bytes_read;
    
    if (WriteFile(hSerial, data, len, &bytes_read, NULL)) {
        // exception
    }
    
    return bytes_read;
}
